<template>
	<view class="container" :class="themeClass">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="nav-bar">
				<view class="nav-back" @tap="goBack">
					<uni-icons type="left" size="20" color="#333"></uni-icons>
					<text class="back-text">返回</text>
				</view>
				<text class="nav-title">绑定邮箱</text>
				<view class="nav-right"></view>
			</view>
		</view>

		<!-- 页面内容 -->
		<view class="content">
			<!-- 说明信息 -->
			<view class="info-section">
				<view class="info-icon">
					<uni-icons type="email" size="40" color="#fa8c16"></uni-icons>
				</view>
				<text class="info-title">绑定邮箱</text>
				<text class="info-desc">绑定邮箱后可用于登录验证、密码找回和重要通知接收</text>
			</view>

			<!-- 绑定表单 -->
			<view class="form-section">
				<!-- 邮箱输入 -->
				<view class="form-item">
					<text class="form-label">邮箱地址</text>
					<view class="input-wrapper">
						<input 
							class="form-input" 
							type="text" 
							placeholder="请输入邮箱地址"
							v-model="emailAddress"
							@input="onEmailInput"
							@blur="validateEmail"
						/>
					</view>
					<text v-if="emailError" class="error-text">{{ emailError }}</text>
				</view>

				<!-- 验证码输入 -->
				<view class="form-item">
					<text class="form-label">验证码</text>
					<view class="input-wrapper code-wrapper">
						<input 
							class="form-input code-input" 
							type="number" 
							placeholder="请输入验证码"
							v-model="verifyCode"
							maxlength="6"
						/>
						<uni-button 
							class="code-btn" 
							size="mini" 
							:disabled="!canSendCode || countdown > 0"
							@tap="sendVerifyCode"
						>
							{{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
						</uni-button>
					</view>
				</view>

				<!-- 绑定按钮 -->
				<uni-button 
					class="bind-btn" 
					type="primary" 
					:disabled="!canBind"
					:loading="isBinding"
					@tap="bindEmail"
				>
					{{ isBinding ? '绑定中...' : '确认绑定' }}
				</uni-button>

				<!-- 温馨提示 -->
				<view class="tips-section">
					<view class="tips-title">
						<uni-icons type="info" size="16" color="#fa8c16"></uni-icons>
						<text class="tips-text">温馨提示</text>
					</view>
					<view class="tips-list">
						<text class="tip-item">• 一个邮箱只能绑定一个账号</text>
						<text class="tip-item">• 绑定后可用于登录验证和找回密码</text>
						<text class="tip-item">• 重要通知将发送到您的邮箱</text>
						<text class="tip-item">• 如需更换邮箱，请联系客服</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import themeManager from '@/utils/theme.js';

export default {
	data() {
		return {
			emailAddress: '',
			verifyCode: '',
			countdown: 0,
			isBinding: false,
			emailError: '',
			themeClass: themeManager.getThemeClass(),
			countdownTimer: null,
			emailRegex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
		}
	},
	computed: {
		canSendCode() {
			return this.emailAddress && this.emailRegex.test(this.emailAddress) && !this.emailError;
		},
		canBind() {
			return this.canSendCode && this.verifyCode.length === 6;
		}
	},
	methods: {
		// 邮箱输入处理
		onEmailInput(e) {
			this.emailAddress = e.detail.value.trim();
			this.emailError = '';
		},

		// 邮箱验证
		validateEmail() {
			if (!this.emailAddress) {
				this.emailError = '';
				return;
			}
			
			if (!this.emailRegex.test(this.emailAddress)) {
				this.emailError = '请输入正确的邮箱格式';
			} else {
				this.emailError = '';
			}
		},

		// ==================== 后端接口定义 ====================
		// 前端人员：发送邮箱验证码
		// BACKEND REQUIRED - 后端开发人员请实现以下接口
		// 
		// POST /api/account/security/send-email-code
		// 请求头: Authorization: Bearer {token}
		// 请求体: {
		//   "email": "user@example.com"    // 邮箱地址
		// }
		// 响应 200: { "success": true, "message": "验证码已发送" }
		// 响应 400: { "success": false, "message": "邮箱格式错误" }
		// 响应 409: { "success": false, "message": "邮箱已被其他账号绑定" }
		// 响应 429: { "success": false, "message": "发送频率过快，请稍后再试" }
		// 响应 500: { "success": false, "message": "发送失败，请稍后重试" }
		// 生成6位随机验证码
		generateRandomCode() {
			return Math.floor(100000 + Math.random() * 900000).toString();
		},

		sendVerifyCode() {
			if (!this.canSendCode || this.countdown > 0) return;

			// 显示加载提示
			uni.showLoading({
				title: '发送中...'
			});

			// 模拟网络延迟
			setTimeout(() => {
				uni.hideLoading();
				
				// 生成6位随机验证码
				const verifyCode = this.generateRandomCode();
				
				// 开始倒计时
				this.countdown = 60;
				this.countdownTimer = setInterval(() => {
					this.countdown--;
					if (this.countdown <= 0) {
						clearInterval(this.countdownTimer);
						this.countdownTimer = null;
					}
				}, 1000);
				
				// 显示验证码（开发阶段）
				uni.showToast({
					title: `验证码: ${verifyCode}`,
					icon: 'none',
					duration: 5000
				});
				
				// 自动填入验证码（开发阶段）
				setTimeout(() => {
					this.verifyCode = verifyCode;
				}, 1000);
				
				console.log(`邮箱 ${this.emailAddress} 的验证码: ${verifyCode}`);
			}, 1000);
		},

		// 前端人员：绑定邮箱
		// BACKEND REQUIRED - 后端开发人员请实现以下接口
		// 
		// POST /api/account/security/bind-email
		// 请求头: Authorization: Bearer {token}
		// 请求体: {
		//   "email": "user@example.com",  // 邮箱地址
		//   "code": "123456"             // 验证码
		// }
		// 响应 200: { "success": true, "message": "绑定成功" }
		// 响应 400: { "success": false, "message": "验证码错误" }
		// 响应 409: { "success": false, "message": "邮箱已被其他账号绑定" }
		// 响应 410: { "success": false, "message": "验证码已过期" }
		// 响应 500: { "success": false, "message": "绑定失败，请稍后重试" }
		bindEmail() {
			if (!this.canBind || this.isBinding) return;

			this.isBinding = true;

			// 显示加载提示
			uni.showLoading({
				title: '绑定中...'
			});

			// 模拟网络延迟
			setTimeout(() => {
				uni.hideLoading();
				
				// 直接处理绑定（开发阶段）
				uni.showToast({ title: '绑定成功', icon: 'success' });
				
				// 通知父页面更新安全信息
				uni.$emit('securityInfoUpdated', {
					type: 'email',
					value: this.emailAddress
				});
				
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
				
				this.isBinding = false;
			}, 1000);
		},

		// 返回上一页
		goBack() {
			uni.navigateBack();
		},

		// 主题变化监听
		handleThemeChange(isNightMode) {
			this.themeClass = themeManager.getThemeClass();
		}
	},

	onLoad() {
		themeManager.addListener(this.handleThemeChange);
	},

	onUnload() {
		themeManager.removeListener(this.handleThemeChange);
		if (this.countdownTimer) {
			clearInterval(this.countdownTimer);
		}
	}
}
</script>

<style>
	page {
		background-color: #f5f6fa;
	}

	.container {
		min-height: 100vh;
		background-color: #f5f6fa;
	}

	/* 顶部导航栏 */
	.header {
		background: #ffffff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		height: 88rpx;
	}

	.nav-title {
		font-size: 18px;
		font-weight: 600;
		color: #333;
	}

	.nav-back {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 10rpx 16rpx;
		border-radius: 8rpx;
		transition: background-color 0.2s ease;
		cursor: pointer;
	}

	.nav-back:active {
		background-color: rgba(0, 0, 0, 0.05);
	}

	.back-text {
		font-size: 16px;
		color: #333;
		font-weight: 500;
	}

	.nav-right {
		width: 40rpx;
	}

	/* 页面内容 */
	.content {
		padding: 40rpx 30rpx;
	}

	/* 说明信息 */
	.info-section {
		text-align: center;
		margin-bottom: 60rpx;
	}

	.info-icon {
		width: 120rpx;
		height: 120rpx;
		background: linear-gradient(135deg, #fa8c16, #ffa940);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 30rpx;
		box-shadow: 0 8rpx 32rpx rgba(250, 140, 22, 0.3);
	}

	.info-title {
		display: block;
		font-size: 24px;
		font-weight: 700;
		color: #333;
		margin-bottom: 16rpx;
	}

	.info-desc {
		display: block;
		font-size: 14px;
		color: #666;
		line-height: 1.6;
		max-width: 500rpx;
		margin: 0 auto;
	}

	/* 表单区域 */
	.form-section {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	}

	.form-item {
		margin-bottom: 40rpx;
	}

	.form-item:last-child {
		margin-bottom: 0;
	}

	.form-label {
		display: block;
		font-size: 16px;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

	.input-wrapper {
		position: relative;
	}

	.form-input {
		width: 100%;
		height: 88rpx;
		background: #f8f9fa;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 16px;
		color: #333;
		box-sizing: border-box;
		transition: all 0.3s ease;
	}

	.form-input:focus {
		border-color: #fa8c16;
		background: #ffffff;
		box-shadow: 0 0 0 4rpx rgba(250, 140, 22, 0.1);
	}

	.error-text {
		display: block;
		font-size: 12px;
		color: #ff4d4f;
		margin-top: 8rpx;
		line-height: 1.4;
	}

	.code-wrapper {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.code-input {
		flex: 1;
	}

	.code-btn {
		flex-shrink: 0;
		height: 88rpx;
		padding: 0 24rpx;
		background: #fa8c16;
		color: #ffffff;
		border-radius: 12rpx;
		font-size: 14px;
		border: none;
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	.code-btn:disabled {
		background: #d9d9d9;
		color: #999;
	}

	.bind-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(135deg, #fa8c16, #ffa940);
		color: #ffffff;
		border-radius: 12rpx;
		font-size: 18px;
		font-weight: 600;
		border: none;
		margin-top: 40rpx;
		box-shadow: 0 4rpx 16rpx rgba(250, 140, 22, 0.3);
		transition: all 0.3s ease;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	.bind-btn:disabled {
		background: #d9d9d9;
		color: #999;
		box-shadow: none;
	}

	.bind-btn:active:not(:disabled) {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(250, 140, 22, 0.3);
	}

	/* 温馨提示 */
	.tips-section {
		margin-top: 40rpx;
		padding: 30rpx;
		background: #fff7e6;
		border-radius: 16rpx;
		border: 2rpx solid #ffe7ba;
	}

	.tips-title {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-bottom: 20rpx;
	}

	.tips-text {
		font-size: 16px;
		font-weight: 600;
		color: #fa8c16;
	}

	.tips-list {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.tip-item {
		font-size: 14px;
		color: #666;
		line-height: 1.6;
	}

	/* 夜间模式适配 */
	.night-mode {
		background-color: #1a1a1a;
	}

	.night-mode .header {
		background: #2c2c2c;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.3);
	}

	.night-mode .nav-title {
		color: #e0e0e0;
	}

	.night-mode .nav-back:active {
		background-color: rgba(255, 255, 255, 0.1);
	}

	.night-mode .back-text {
		color: #e0e0e0;
	}

	.night-mode .form-section {
		background: #2c2c2c;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
	}

	.night-mode .form-label {
		color: #e0e0e0;
	}

	.night-mode .form-input {
		background: #3a3a3a;
		border-color: #4a4a4a;
		color: #e0e0e0;
	}

	.night-mode .form-input:focus {
		border-color: #fa8c16;
		background: #3a3a3a;
	}

	.night-mode .info-title {
		color: #e0e0e0;
	}

	.night-mode .info-desc {
		color: #b0b0b0;
	}

	.night-mode .tips-section {
		background: #2a2a2a;
		border-color: #3a3a3a;
	}

	.night-mode .tip-item {
		color: #b0b0b0;
	}

	.night-mode .error-text {
		color: #ff7875;
	}
</style>
